<?php
/**
 * 用户控制器
 * User: xuyiping(xuyiping@liangzihuzhu.com.cn)
 * Date: 2017/11/29
 * Time: 15:25
 */

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Model\User\DepartmentModel;
use App\Model\User\RoleModel;
use App\Model\User\RolePermissionModel;
use App\Model\User\UserModel;
use App\Model\User\UserRoleModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    protected $permission = 0;
    public function index(){

        $department_obj = new DepartmentModel();

        //无限级查询部门数据
        $department = $department_obj->getDepartments(0);

        //生成部门列表
        $department_html = $department_obj->getDepartmentsHtml($department);

        //生成部门select选项
        $department_select_html = $department_obj->getDepartmentsSelectHtml($department);

        //查询角色信息
        $role = RoleModel::select('roleID', 'roleName')->get();
        if ($role) {
            $role = $role->toJson();
        }

        $data = [
            'department_html' => $department_html,
            'department_select_html' => $department_select_html,
            'role' => $role,
        ];

        return view('Admin/system/user/index', $data);
    }

    /**
     * ajax 表格查询
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search( Request $request){

        $where = [];

        //查询条件
        if ($request->input('trueName')) {
            $where['trueName'] = $request->input('trueName');
        }


        //分页查询用户
        if ($request->input('departmentID')) {

            //获取当前部门下的所有下级部门
            $department_obj = new DepartmentModel();
            $department_id = $department_obj->getDepartmentsId($request->input('departmentID'), [$request->input('departmentID')]);

            $user = UserModel::whereIn('departmentID', $department_id)
                ->where($where)
                ->orderBy($request->input('sort'), $request->input('order'))
                ->paginate($request->input('limit'))
                ->toArray();

        } else {

            $user = UserModel::where($where)
                ->orderBy($request->input('sort'), $request->input('order'))
                ->paginate($request->input('limit'))
                ->toArray();
        }

        //返回数组
        $res_data = [
            'total' => $user['total'],
            'rows' => []
        ];

        foreach ( $user['data'] as &$row ) {

            $operation = '<a href="javascript: void(0);" onclick="User.del(\'' . $row['uuid'] . '\');">删除</a>&nbsp&nbsp';
            $operation .= '<a href="javascript: void(0);" onclick="User.edit(\'' . $row['uuid'] . '\');">修改</a>&nbsp&nbsp';

            $res_data['rows'][] = array(
                'operation' => $operation,
                'trueName' => $row['trueName'],
                'departmentName' => $row['departmentName'],
                'email' => $row['email'],
                'mobile' => $row['mobile'],
            );
        }

        return response()->json($res_data);

    }

    /**
     * ajax 添加用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request) {

        $uuid = $request->input('uuid');
        $userID = $request->input('userID');
        $trueName = $request->input('trueName');
        $departmentID = $request->input('departmentID');
        $email = $request->input('email');
        $mobile = $request->input('mobile');
        $roleID = $request->input('roleID');
        $personLiable = $request->input('personLiable');

        if (empty($userID)) {
            return response()->json(['code' => 100001, 'message' => '用户名不能为空']);
        }

        if (empty($trueName)) {
            return response()->json(['code' => 100002, 'message' => '真实姓名不能为空']);
        }

        if (!ebsig_is_int($departmentID)) {
            return response()->json(['code' => 100003, 'message' => '所属部门不能为空']);
        }

        if (!isEmail($email)) {
            return response()->json(['code' => 100004, 'message' => 'email不能为空']);
        }

        if (!isMobile($mobile)) {
            return response()->json(['code' => 100005, 'message' => '手机号码不能为空']);
        }

        if (!ebsig_is_int($roleID)) {
            return response()->json(['code' => 100006, 'message' => '用户角色不能为空']);
        }

        //检查用户名是否已存在
        $check_user = UserModel::select('uuid')->find($userID);
        if ($check_user && $check_user->uuid != $uuid) {
            return response()->json(['code' => 100007, 'message' => '用户名已存在']);
        }

        //检查手机号码是否存在
        $check_user = UserModel::select('uuid')->where('mobile', $mobile)->first();
        if ($check_user && $check_user->uuid != $uuid) {
            return response()->json(['code' => 100008, 'message' => '手机号码已被其他用户使用']);
        }

        //检查email是否存在
        $check_user = UserModel::select('uuid')->where('email', $email)->first();
        if ($check_user && $check_user->uuid != $uuid) {
            return response()->json(['code' => 100009, 'message' => 'email已被其他用户使用']);
        }

        //检查部门是否存在
        $department = DepartmentModel::select('departmentName')->find($departmentID);
        if (!$department) {
            return response()->json(['code' => 100010, 'message' => '部门信息不存在']);
        }

        //检查角色是否存在
        $role = RoleModel::select('roleID')->find($roleID);
        if (!$role) {
            return response()->json(['code' => 100011, 'message' => '角色信息不存在']);
        }

        try {

            DB::beginTransaction();

            //新增修改用户信息
            if ($uuid) {
                $user = UserModel::where('uuid', $uuid)->first();
                if (!$user) {
                    throw new Exception('用户不存在', 100012);
                }
                $user->timeStamp = date('Y-m-d H:i:s');

            } else {
                $user = new UserModel;
                $user->uuid = makeUuid();
                $user->timeStamp = date('Y-m-d H:i:s');
                $user->createTime = date('Y-m-d H:i:s');
                $user->creator = session('ADMIN_USER_ID');
                $user->userID = $userID;
                $user->pwdFlg = 0;
                $user->useFlg = 1;
                $user->userPwd = md5('kkkkkk');
            }

            $user->trueName = $trueName;
            $user->departmentID = $departmentID;
            $user->departmentName = $department->departmentName;
            $user->email = $email;
            $user->mobile = $mobile;
            $user->personLiable = $personLiable ;
            $user->save();

            //新增修改门店角色信息
            $user_role = UserRoleModel::find($userID);
            if (!$user_role) {

                $user_role = new UserRoleModel();
                $user_role->uuid = makeUuid();
                $user_role->timeStamp = date('Y-m-d H:i:s');
                $user_role->createTime = date('Y-m-d H:i:s');
                $user_role->creator = session('ADMIN_USER_ID');
                $user_role->userID = $userID;
            } else {

                $user_role->timeStamp = date('Y-m-d H:i:s');
            }

            $user_role->roleID = $roleID;
            $user_role->save();

            DB::commit();

        } catch (Exception $e) {
            DB::rollBack();

            return response()->json(['code' => $e->getCode(), 'message' => $e->getMessage()]);
        }

        return response()->json(['message' => 'ok', 'code'=> 200]);

    }


    /**
     * 删除用户
     * @param string $uuid 表唯一字段
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($uuid)
    {
        $user = UserModel::where('uuid', $uuid)->first();
        if (!$user) {
            return response()->json(['code' => 100000, 'message' => '用户信息没有找到']);
        }

        try {

            DB::beginTransaction();

            //删除用户
            $user->delete();

            //删除用户角色
            $user_role = UserRoleModel::find($user->userID);
            if ($user_role) {
                $user_role->delete();
            }

            DB::commit();

        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['code' => $e->getCode(), 'message' => $e->getMessage()]);
        }

        return response()->json(['message' => 'ok', 'code'=> 200]);
    }

    /**
     * 查询单个用户信息
     * @param string $uuid 用户uuid
     * @return \Illuminate\Http\JsonResponse
     **/
    public function get($uuid)
    {

        //查询用户信息
        $user = UserModel::where('uuid', $uuid)->first();
        if (!$user) {
            return response()->json(['code' => 400, 'message' => '会员信息没有找到']);
        }

        //查询用户角色信息
        $user_role = UserRoleModel::select('roleID')->find($user->userID);

        return response()->json([
            'code' => 200,
            'message' => 'ok',
            'data' => [
                'userID' => $user->userID,
                'trueName' => $user->trueName,
                'email' => $user->email,
                'mobile' => $user->mobile,
                'departmentID' => $user->departmentID,
                'roleID' => $user_role->roleID,
                'personLiable' => $user->personLiable
            ]
        ]);

    }

    /*
     * 修改用户密码
     * return true|false
     */
    public function editPwd(Request $request) {

        $oldPwd = $request->input('oldPwd');
        $newPwd = $request->input('newPwd');
        $userId =  session('ADMIN_USER_ID' . session()->getId());   // 获取当前用户

        if (empty($oldPwd)) {
            return response()->json(['code' => 100001, 'message' => '请输入旧密码']);
        }

        if (empty($newPwd)) {
            return response()->json(['code' => 100002, 'message' => '请输入新密码']);
        }

        if (!is_pwd($newPwd)) {
            return response()->json(['code' => 100003, 'message' => '新密码格式不正确']);
        }

        if ( $newPwd == '12345678' ) {
            return response()->json(['code' => 100004, 'message' => '新的密码不能为12345678']);
        }

        //查询用户数据
        $user = UserModel::find($userId);

        if (!$user) {
            return response()->json(['code' => 100005, 'message' => '当前用户不存在']);
        }

        if ( $user->userPwd != md5($oldPwd)) {
            return response()->json(['code' => 100006, 'message' => '当前用户密码输入错误']);
        }

        if ($newPwd == $oldPwd) {
            return response()->json(['code' => 100007, 'message' => '新的密码不能和原密码相同']);
        }

        $user->userPwd = md5($newPwd);
        $user->pwdFlg = 1;
        $user->save();

        return response()->json(['code' => 200, 'message' => 'ok']);

    }
}